import groupMembersSqlite from "@/sqlite_services/group_members.js"
import groupMembersApi from "@/services/api/group_members.js"
export default {
    state: {
        chatInfo:null,
		chatGroupInfo:null,//聊天中群的资料
		chatTopMsg:null,//群聊天中的置顶消息
		
		groupMemberOnline: {}, // 聊天中在线群成员
		groupTotal: 0, // 聊天中群成员
		onlineTimer: null, // 获取在线好友和群成员的计时器
    },
    mutations: {
        setChatInfo(state, data) {
			state.chatInfo = data
        },
		//更新内容
		updateChatInfo(state, {uuid,data}) {
			// 判断ID是否相同
			if (state.chatInfo && state.chatInfo.uuid == uuid) {
				for (let key in data) {
					if (data[key] != state.chatInfo[key]) {
						Vue.set(state.chatInfo, key, data[key]);
					}
				}
			}
		},
		//设置聊天中群的资料
		setChatGroupInfo(state, data) {
			state.chatGroupInfo = data
		},
		//更新聊天中群的资料
		updateChatGroupInfo(state, data) {
			// 判断ID是否相同
			if (state.chatGroupInfo && state.chatGroupInfo.group_id == data.group_id) {
				for (let key in data) {
					if (data[key] != state.chatGroupInfo[key]) {
						Vue.set(state.chatGroupInfo, key, data[key]);
					}
				}
			}
		},
		//设置群聊天置顶消息
		setChatTopMsg(state, {data,target_id}) {
			if (state.chatInfo && state.chatInfo.uuid == target_id) {
				state.chatTopMsg = data
			}
		},
		editChatTopMsg(state, data) {
			state.chatTopMsg = {
				...state.chatTopMsg,
				...data
			}
		},
		//设置在线群成员
		SET_GROUP_MEMBER_ONLINE(state, {onlineMembers,total}) {
			state.groupMemberOnline = onlineMembers;
			state.groupTotal = total;
		},
		//群成员查询在线的计时器
		SET_GROUP_ONLINE_TIMER(state, timer) {
			state.onlineTimer = timer;
		},
		//关闭计时器
		CLEAR_GROUP_ONLINE_TIMER(state) {
			if (state.onlineTimer) {
				clearInterval(state.onlineTimer);
				state.onlineTimer = null;
			}
		},
    },
    actions: {
		async getOnlineGroupMember({ commit },group_id) {
			try {
				let resList = await groupMembersApi.onlineGroupMember(group_id);
				if(resList){
					let onlineGroupMembers = resList.list.reduce((acc, id) => {
						acc[id] = true;
						return acc;
					}, {});
					commit('SET_GROUP_MEMBER_ONLINE', {
						onlineMembers:onlineGroupMembers,
						total:resList.count || 0
					});
					
				}else{
					commit('SET_GROUP_MEMBER_ONLINE', {
						onlineMembers:{},
						total:0
					});
				}
			} catch (error) {
				console.error('获取在线群成员失败:', error);
			}
		},
		startGroupOnlineTimer({ dispatch, commit },group_id) {
			dispatch('stopGroupOnlineTimer')//每次开始前清除一下
			dispatch('getOnlineGroupMember',group_id); // 立即获取一次在线群成员
			let timer = setInterval(() => {
				dispatch('getOnlineGroupMember',group_id);
			}, 30000); // 每30秒获取一次
			commit('SET_GROUP_ONLINE_TIMER', timer);
		},
		//关闭时还应该去掉
		stopGroupOnlineTimer({ commit }) {
			commit('CLEAR_GROUP_ONLINE_TIMER');
			commit('SET_GROUP_MEMBER_ONLINE', {
				onlineMembers:{},
				total:0
			});
		},
    }
};